import React, { useEffect, useRef, useState, useImperativeHandle, forwardRef } from 'react';
import { Divider, Descriptions, Modal, Form, Button, Spin, Popconfirm } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { useModel } from 'umi';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import { 
  getPlanSettleList,
  settleOrCancelSettle as doSettleOrCancelSettle,
  updateSettle, managerCancel } from '@/services/order/api';
import { showMsg, MsgType, isSupportSticky } from '@/utils/utils';
import OrderDetail from '@/components/OrderInfo';
import PermissionControl from '@/components/PermissionControl';

type SettleItem = {
  sett_id?: string;
  bill_begin_date?: string;
  bill_end_date?: string;
  total_bill_price?: string;
  discount?: string;
  sett_price?: number;
  sett_type?: string;
  sett_no?: number;
  sett_status?: string;
  create_user_name?: string;
  remarks?: string;
}

type SettleItemList = {
  record_list: SettleItem[];
  sum_record_num: number;
  total_price: string;
  total_discount_price: string;
  total_sett_price: string;
  total_suc_sett_price: string;
  total_wait_sett_price: string;
  total_going_sett_price: string;
}
interface SettlementInfoProps {
  order_id?: string;
  ref?: any;
  cancelSettle: () => void;
  onRefresh: () => void;
  dischargeStatus?: string;
  reload?: Function;
}

const SettlementInfo: React.FC<SettlementInfoProps> = forwardRef((props, ref) => {
  const { order_id = '', cancelSettle, onRefresh, reload } = props;
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [printing, setPrinting] = useState(false); // 是否弹出打印窗口
  const [loading, setLoading] = useState<boolean>(false);
  const { initialState } = useModel('@@initialState');
  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色
  const { confirm } = Modal;

  // 结算详情弹窗
  const [settDetailDialog, setSettDetailDialog] = useState<boolean>(false);

  const [currentRow, setCurrentRow] = useState<SettleItem>({});

  // 结算详细数据
  const [settleData, setSettleData] = useState<SettleItemList>({} as SettleItemList);

  /**
   * 结算或取消结算
   */
   const settleOrCancelSettle = async (record: SettleItem, sett_status: string) => {
    try {
      const { sett_id } = record;
      await doSettleOrCancelSettle({
        order_id,
        sett_id: sett_id as string,
        sett_status: sett_status
      });
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  }

  // 取消支付
  const cancelCurOrder = async(record) => {
    setLoading(true);
    console.log('record', record);
    if (record.manager_flag === 'Y') {
      await managerCancel(record.manager_order_id).then(res => {
        setLoading(false);
        showMsg('已取消结算', 'success');
        actionRef.current?.reload();
        cancelSettle?.();
        setSettDetailDialog(false);
      }).catch(error => {
        showMsg(error?.data?.errmsg)
      });
    } else {
      await settleOrCancelSettle(record, 'U').then(res => {
        setLoading(false);
        showMsg('已取消结算', 'success');
        actionRef.current?.reload();
        cancelSettle?.();
        setSettDetailDialog(false);
      }).catch(error => {
        showMsg(error?.data?.errmsg)
      });
    }
  }


  const columns: ProColumns<SettleItem>[] = [
    {
      title: '账单开始日期',
      dataIndex: 'bill_begin_date',
      editable: false,
      width: 85
    },
    {
      title: '账单结束日期',
      dataIndex: 'bill_end_date',
      editable: false,
      width: 85
    },
    {
      title: '账单费用',
      dataIndex: 'total_bill_price',
      editable: false,
      align: 'right',
      valueType: 'money',
      width: 100
    },
    {
      title: '折扣',
      dataIndex: 'discount',
      valueType: 'digit',
      align: 'right',
      width: 50,
      editable: initialState?.canDiscount,
      fieldProps: (form, record) => {
        return {
          style: {
            maxWidth: '100%'
          },
          precision: 2,
          max: Number.MAX_SAFE_INTEGER,
          min: Number.MIN_SAFE_INTEGER,
          onChange: (value: any) => {
            console.log(value);
            if (isNaN(value)) {
              return;
            }
            if (value <= 0 || value > 1) {
              form.validateFields();
              return;
            }
            const item: SettleItem = form.getFieldsValue()[record.rowKey as string];
            item['sett_price'] = +Number(Number(currentRow.total_bill_price) * value).toFixed(2);
            form.setFieldsValue({ [record.rowKey || '']: item });
          },

          onBlur: (e: any) => {
            const value = e.target.value;
            if (isNaN(value)) {
              return;
            }
            if (Number(value) <= 0 || Number(value) > 1) {
              form.validateFields();
              return;
            }
          }
        }
      },
      formItemProps: () => {
        return {
          rules: [
            {
              required: true,
              message: '此项是必填项'
            },
            {
              validator: (rule, value) => {
                if (value <= 0 || value > 1) {
                  return Promise.reject(`折扣输入有误`);
                }
                return Promise.resolve();
              },
              message: '请输入大于0且小于1的数字'
            }
          ]
        }
      }
    },
    {
      title: '结算金额',
      dataIndex: 'sett_price',
      align: 'right',
      valueType: 'money',
      width: 100,
      editable: initialState?.canDiscount,
      fieldProps: (form, record) => {
        return {
          min: Number.MIN_SAFE_INTEGER,
          max: Number.MAX_SAFE_INTEGER,
          precision: 2,
          onChange: (value: any) => {
            if (isNaN(value)) {
              return;
            }
            if (value <= 0 || value > (Number(settleData.total_wait_sett_price) || 0.01)) {
              form.validateFields();
              return;
            }

            const item: SettleItem = form.getFieldsValue()[record.rowKey as string];
            item['discount'] = Number(value / Number(currentRow.total_bill_price)).toFixed(2);
            form.setFieldsValue({ [record.rowKey || '']: item });
          },

          onBlur: (e: any) => {
            const value = e.target.value;
            if (isNaN(value)) {
              return;
            }

            if (Number(value) <= 0 || Number(value) > (Number(settleData.total_wait_sett_price))) {
              form.validateFields();
              return;
            }
          }
        }
      },
      formItemProps: () => {
        return {
          rules: [
            {
              required: true,
              message: '此项是必填项'
            },
            {
              validator: (rule, value) => {
                if (value <= 0 || value > (+settleData.total_wait_sett_price || 0.01)) {
                  return Promise.reject(`金额输入有误`);
                }
                return Promise.resolve();
              },
              message: `请输入大于0的数字且最大可输入金额${Number(settleData.total_wait_sett_price) || 0.01}元`
            }
          ]
        }
      }
    },
    {
      title: '结算类型',
      dataIndex: 'sett_type',
      editable: false,
      valueType: 'select',
      valueEnum: {
        S: '计停结算',
        T: '临时结算',
        O: '出院结算'
      },
      width: 60
    },
    {
      title: '结算单号',
      dataIndex: 'sett_no',
      editable: false,
      width: 190
    },
    {
      title: '结算状态',
      dataIndex: 'sett_status',
      editable: false,
      valueType: 'select',
      valueEnum: {
        U: '待结算',
        G: '结算中',
        P: '已结算'
      },
      width: 60
    },
    {
      title: '单据创建人',
      dataIndex: 'create_user_name',
      editable: false,
      width: 70
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      className: 'wordbreak',
      width: 120
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      width: 120,
      // fixed: 'right',
      // fixed: isSupportSticky() ? 'right' : '',
      render: (_, record: SettleItem, index: number, action) => {
        // U：待结算，G：结算中，P：已结算 ,
        const { sett_status, manager_flag } = record;

        if (sett_status === 'P') {
          return [
            <PermissionControl key="view" action_id="400401016">
              <a onClick={() => {
                setSettDetailDialog(true);
                setCurrentRow(record);
              }}>查看</a>
            </PermissionControl>
          ]
        } 

        if (sett_status === 'G') {
          return [
            <PermissionControl key="view" action_id="400401016">
              <a onClick={() => {
                setSettDetailDialog(true);
                setCurrentRow(record);
              }}>查看</a>
            </PermissionControl>,
            // manager_flag !== 'Y' &&
            <PermissionControl key="cancel" action_id="400401019">
              <Popconfirm 
                placement="topRight"
                key="cancel"
                title={record.manager_flag === 'Y' ? '该笔订单已经通过出院办结发起结算，是否确认取消？' : ''}
                onConfirm={async () => cancelCurOrder(record)}
                okText="确认取消"
                disabled={record.manager_flag !== 'Y'}
                cancelText="再想想">
                  <a onClick={() => {
                    if (record.manager_flag !== 'Y') {
                      cancelCurOrder(record)
                    }
                  }}>取消</a>
              </Popconfirm>
            </PermissionControl>
          ]
        } 

        // 已办结出院
        if (manager_flag === 'Y') {
          return [
            <PermissionControl key="view" action_id="400401016">
              <a onClick={() => {
                setSettDetailDialog(true);
                setCurrentRow(record);
              }}>查看</a>
            </PermissionControl>,
            <PermissionControl key="cancel" action_id="400401019">
              <Popconfirm 
                placement="topRight"
                key="cancel"
                title={record.manager_flag === 'Y' ? '该笔订单已经通过出院办结发起结算，是否确认取消？' : ''}
                onConfirm={async () => cancelCurOrder(record)}
                okText="确认取消"
                disabled={record.manager_flag !== 'Y'}
                cancelText="再想想">
                  <a onClick={() => {
                    if (record.manager_flag !== 'Y') {
                      cancelCurOrder(record)
                    }
                  }}>取消</a>
              </Popconfirm>
            </PermissionControl>
          ]
        }

        return [
          <PermissionControl key="edit" action_id="400401017">
            <a onClick={() => {
              action?.startEditable?.(record.sett_id as string);
              setCurrentRow(record);
            }}>编辑</a>
          </PermissionControl>,
          <PermissionControl key="settle" action_id="400401018">
            <a onClick={() => {
              setSettDetailDialog(true);
              setCurrentRow(record);
            }}>结算</a>
          </PermissionControl>,
          <PermissionControl key="cancel" action_id="400401019">
            <Popconfirm 
              placement="topRight"
              key="cancel"
              title={record.manager_flag === 'Y' ? '该笔订单已经通过出院办结发起结算，是否确认取消？' : ''}
              onConfirm={async () => cancelCurOrder(record)}
              okText="确认取消"
              disabled={record.manager_flag !== 'Y'}
              cancelText="再想想">
                <a onClick={() => {
                  if (record.manager_flag !== 'Y') {
                    cancelCurOrder(record)
                  }
                }}>取消</a>
            </Popconfirm>
          </PermissionControl>
        ]
      }
    }
  ]


  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    reload: () => actionRef.current?.reload(),
    clear: () => {
      actionRef.current?.reload();
    },
  }))

  const optCallback = (data: any) => {
    setSettDetailDialog(false);
    // 提交支付
    const orderSumbitConfig = {
      title: '',
      content: `订单提交成功，请在【${data?.pay_valid_time}】前完成缴费`,
      cancelText: '知道了',
      okText: '打印结算单',
      onOk() {
        console.log('OK');
        setSettDetailDialog(true);
        setPrinting(true);
      },
      onCancel() {
        setSettDetailDialog(true);
        actionRef.current?.reload();
      }
    };
    confirm(orderSumbitConfig);
    actionRef.current?.reload();
  }

  useEffect(() => {
    if (order_id) {
      actionRef.current?.reload();
    }
  }, [order_id]);

  return <Spin spinning={loading}><div className="service-record">
      <div className="header">
        <div className="title">4. 结算单信息</div>
      </div>

      <Divider style={{margin: '10px 0'}} />

      <Button 
        style={{ marginBottom: 10 }}
        onClick={() => {
          // actionRef.current?.reloadAndRest?.();
          onRefresh();
        }} 
        icon={<ReloadOutlined />} 
        type="primary">
        刷新
      </Button>

      <EditableProTable<SettleItem, COMMON.PageParams & {order_id: string;}>
        rowKey="sett_id"
        actionRef={actionRef}
        options={false}
        className="plan-settle-table"
        bordered
        cardBordered
        title={
          () => {
            return order_id && <Descriptions>
            <Descriptions.Item style={{paddingBottom: '0 !important', fontSize: 12}}>
              总金额（<span style={{fontWeight: 'bold', fontSize: '12px'}}>{settleData.total_price}</span> 元）-   
              折扣金额（<span style={{fontWeight: 'bold', fontSize: '12px'}}>{settleData.total_discount_price}</span> 元） =    
              结算金额（<span style={{fontWeight: 'bold', fontSize: '12px'}}>{settleData.total_sett_price}</span> 元） =   
              已结算金额（<span style={{fontWeight: 'bold', fontSize: '12px'}}>{settleData.total_suc_sett_price}</span> 元） +   
              待结算金额（<span style={{fontWeight: 'bold', fontSize: '12px'}}>{settleData.total_wait_sett_price}</span> 元） +   
              结算中（<span style={{fontWeight: 'bold', fontSize: '12px'}}>{settleData.total_going_sett_price}</span> 元）
            </Descriptions.Item>
          </Descriptions>
          }
        }
        request={async (params) => {
          if (!order_id) {
            return {
              data: [],
              total: 0,
              success: true
            }
          }
          try {
            params = Object.assign({}, params, { order_id });
            const data: SettleItemList = await getPlanSettleList(params);
            setSettleData(data);
            return {
              data: data.record_list,
              total: data.sum_record_num,
              success: true
            }
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              total: 0,
              success: true
            }
          }
        }}
        search={false}
        // scroll={{ x: 1000 }}
        recordCreatorProps={false}
        editable={
          {
            form,
            editableKeys,
            onChange: setEditableRowKeys,
            onSave: async (key, row) => {
              try {
                console.log(row);
                const params = {
                  order_id,
                  remarks: row.remarks,
                  sett_price: row.sett_price,
                  sett_id: row.sett_id,
                  discount: row.discount
                }
                await updateSettle(params);
                actionRef.current?.reload();
                return true;
              } catch (error) {
                showMsg(error?.data?.errmsg);
                actionRef.current?.reload();
                return false;
              }
            },

            actionRender: (row, config, defaultDom) => [defaultDom.save, defaultDom.cancel],

            onCancel: async (key, row, originRow) => {
              form.resetFields();
            }
          }
        }
        pagination={{
          showQuickJumper: true
        }}
        columns={columns}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.sett_id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        rowClassName={(record) => {
          return record.sett_id === clickRow ? 'tableRowClick' : ''
        }}
      />

       {
        settDetailDialog && <OrderDetail 
          title="结算信息"
          type='settleInfo'
          order_id={order_id}
          isPrint={printing}
          handleModalVisible={(visible: boolean) => {
            setSettDetailDialog(visible);
            onRefresh?.();
          }}
          record={currentRow}
          optCallback={optCallback}
          cancelOrder={() => cancelCurOrder(currentRow)}
        />
      }
  </div></Spin>
});
export default SettlementInfo;